<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-container">
      <uni-search-bar
        v-model="searchValue"
        placeholder="搜索商品"
        @confirm="search"
        :radius="100"
        bgColor="#f5f5f5"
        cancelButton="none"
      />
    </view>

    <!-- 轮播图 -->
    <swiper
      class="swiper"
      :indicator-dots="true"
      :autoplay="true"
      :interval="3000"
      :duration="1000"
    >
      <swiper-item v-for="(item, index) in banners" :key="index">
        <image :src="item.image" mode="aspectFill" class="swiper-image" />
      </swiper-item>
    </swiper>

    <!-- AI推荐商品 -->
    <view class="seckill-goods">
      <view class="header">
        <text class="title">AI猜你喜欢</text>
        <text class="more">查看更多 ></text>
      </view>

      <view class="seckill-items">
        <view
          v-for="(item, index) in seckillGoods"
          :key="index"
          class="seckill-item"
        >
          <image :src="item.mainPic" mode="aspectFill" class="goods-image" />
          <view class="goods-info">
            <text class="goods-name">{{ item.spuName }}</text>
            <text class="goods-desc">{{ item.brief }}，{{ item.unit }}</text>

            <view class="remain-info">
              <text class="remain-text"
                >仅剩：{{ item.spuStockQuantity }}{{ item.unit }}</text
              >
            </view>

            <view class="price-action">
              <view class="price-info">
                <text class="current-price">¥{{ item.minPrice }}</text>
                <text class="original-price" v-if="item.linePrice">¥{{ item.linePrice }}</text>
              </view>
              <button class="buy-btn" @click.stop="navToDetail(item.spuId)">
                马上抢购
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <!-- 标签切换 -->
      <view class="goods-tabs">
        <text
          class="tab-item"
          :class="{ active: currentTab === 'new' }"
          @tap="switchTab('new')"
          >最新特产</text
        >
        <text
          class="tab-item"
          :class="{ active: currentTab === 'fresh' }"
          @tap="switchTab('fresh')"
          >时令生鲜</text
        >
        <text
          class="tab-item"
          :class="{ active: currentTab === 'eco' }"
          @tap="switchTab('eco')"
          >生态乡货</text
        >
      </view>

      <!-- 品网格 -->
      <view class="goods-grid">
        <view
          class="goods-item"
          v-for="(item, index) in goodsList"
          :key="item.spuId"
          @click="navToDetail(item.spuId)"
        >
          <image
            :src="item.mainPic"
            mode="aspectFill"
            class="goods-image"
            @error="() => handleImageError(index)"
          />
          <view class="goods-info">
            <text class="goods-name">{{ item.spuName }}</text>
            <view class="price-box">
              <view class="price-info">
                <text class="current-price">¥{{ item.minPrice }}</text>
                <text class="original-price" v-if="item.linePrice">¥{{ item.linePrice }}</text>
              </view>
              <view class="cart-btn" @click.stop="addToCart(item)">
                <uni-icons type="plus" size="20" color="#ff4444"></uni-icons>
              </view>
            </view>
            <view class="sold-info">
              <text class="sold-count">已售{{ item.soldCount }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态显示 -->
    <view class="empty-state" v-if="goodsList.length === 0 && !isLoading">
      <text>暂无商品数据</text>
    </view>

    <!-- 加载更多 -->
    <uni-load-more :status="loadMoreStatus" />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { goodsService, categoryService } from "@/services";

// 响应式数据定义
const searchValue = ref("");  // 搜索关键词
const banners = ref([        // 轮播图数据
  { image: "/static/banner/1.png" },
  { image: "/static/banner/2.png" },
  { image: "/static/banner/3.png" },
  { image: "/static/banner/4.png" },
  { image: "/static/banner/5.png" },
  { image: "/static/banner/6.png" },
]);
const topCategories = ref([]); // 顶部分类列表
const goodsList = ref([]);     // 商品列表
const page = ref(1);           // 当前页码
const pageSize = ref(10);      // 每页数量
const loadMoreStatus = ref("more"); // 加载更多状态：more-可加载 loading-加载中 noMore-没有更多
const isLoading = ref(false);      // 是否正在加载
const currentTab = ref("new");     // 当前选中的标签
const seckillGoods = ref([]);      // AI推荐商品列表

// 方法定义
// 初始化数据：获取分类、商品列表和推荐商品
const initData = async () => {
  uni.showLoading({
    title: "加载中...",
  });

  try {
    await Promise.all([
      getTopCategories(),
      getGoodsList(),
      getSeckillGoods(),
    ]);
  } catch (error) {
    console.error("初始化数据失败:", error);
  } finally {
    uni.hideLoading();
  }
};

// 获取顶部分类列表
const getTopCategories = async () => {
  try {
    const result = await categoryService.getTopCategories();
    topCategories.value = result.data || [];
  } catch (error) {
    console.error("获取分类失败:", error);
  }
};

// 获取商品列表
const getGoodsList = async () => {
  if (isLoading.value || loadMoreStatus.value === "noMore") return;

  isLoading.value = true;
  loadMoreStatus.value = "loading";

  try {
    const params = {
      pageIndex: page.value,
      pageSize: pageSize.value,
      sortBy: "CreateTime",
      sortType: "desc",
    };

    const res = await goodsService.getGoodsList(params);
    console.log("商品列表返回数据:", res);

    if (res.success && Array.isArray(res.data)) {
      // 转换商品数据格式
      const goodsListData = res.data.map((item) => ({
        spuId: item.spuId,
        spuName: item.title,
        mainPic: item.primaryImage,
        minPrice: item.salePrice || 0,
        linePrice: item.linePrice || 0,
        soldCount: item.soldQuantity || 0,
      }));

      if (page.value === 1) {
        goodsList.value = goodsListData;
      } else {
        goodsList.value = [...goodsList.value, ...goodsListData];
      }

      loadMoreStatus.value = goodsList.value.length >= res.total ? "noMore" : "more";
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    uni.showToast({
      title: "获取商品列表失败",
      icon: "none",
    });
    loadMoreStatus.value = "more";
  } finally {
    isLoading.value = false;
  }
};

// 搜索商品
const search = () => {
  if (!searchValue.value.trim()) return;
  uni.navigateTo({
    url: `/pages/goods/search?keyword=${searchValue.value}`,
  });
};

// 跳转到分类页
const navToCategory = (e) => {
  const category = topCategories.value[e.detail.index];
  uni.navigateTo({
    url: `/pages/category/category?id=${category.id}`,
  });
};

// 跳转到商品详情页
const navToDetail = (spuId) => {
  uni.navigateTo({
    url: `/pages/goods/detail?spuId=${spuId}`,
  });
};

// 处理商品图片加载失败
const handleImageError = (index) => {
  if (goodsList.value[index]) {
    goodsList.value[index].mainPic = "/static/default-goods.png";
  }
};

// 切换标签
const switchTab = (tab) => {
  currentTab.value = tab;
};

// 添加到购物车
const addToCart = (item) => {
  uni.showToast({
    title: "已加入购物车",
    icon: "success",
  });
};

// 获取AI推荐商品
const getSeckillGoods = async () => {
  try {
    const res = await goodsService.getGoodsList({
      pageIndex: 1,
      pageSize: 2,
      sortBy: "Random",
    });

    if (res.success && Array.isArray(res.data)) {
      seckillGoods.value = res.data.map((item) => ({
        ...item,
        spuId: item.spuId,
        spuName: item.title,
        mainPic: item.primaryImage,
        minPrice: item.salePrice || 0,
        linePrice: item.linePrice || 0,
        brief: item.brief || "限时特惠",
        remainingTime: "23:59:59",
        spuStockQuantity: item.spuStockQuantity || 0,
        unit: item.unit || '件'
      }));
    }
  } catch (error) {
    console.error("获取推荐商品失败:", error);
  }
};

// 生命周期钩子
onMounted(() => {
  initData();
});

// 页面生命周期
onLoad(() => {
  initData();
});

// 下拉刷新处理
onPullDownRefresh(() => {
  page.value = 1;
  initData().then(() => {
    uni.stopPullDownRefresh();
  });
});

// 触底加载更多
onReachBottom(() => {
  if (loadMoreStatus.value === "noMore") return;
  page.value++;
  getGoodsList();
});
</script>

<style lang="scss">
@mixin text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.container {
  padding-bottom: 20rpx;
}

.swiper {
  width: 100%;
  height: 350rpx;

  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

.grid-item-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;

  .category-icon {
    width: 60rpx;
    height: 60rpx;
    margin-bottom: 10rpx;
  }

  .category-text {
    font-size: 24rpx;
    color: #333;
  }
}

.goods-list {
  margin-top: 20rpx;
  padding: 0 20rpx;
  min-height: 200rpx;

  .goods-tabs {
    display: flex;
    justify-content: space-around;
    padding: 20rpx 0;

    .tab-item {
      font-size: 28rpx;
      color: #333;
      padding: 10rpx 20rpx;
      border-radius: 12rpx;
      transition: all 0.3s;

      &.active {
        background-color: #ff4444;
        color: #fff;
      }
    }
  }

  .goods-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    padding: 20rpx 0;
  }

  .goods-item {
    background: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

    .goods-image {
      width: 100%;
      height: 340rpx;
      background-color: #f5f5f5;
    }

    .goods-info {
      padding: 16rpx;

      .goods-name {
        font-size: 28rpx;
        color: #333;
        line-height: 1.4;
        height: 80rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }

      .price-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12rpx;

        .price-info {
          display: flex;
          align-items: baseline;

          .current-price {
            font-size: 32rpx;
            color: #ff4444;
            font-weight: bold;
          }

          .original-price {
            font-size: 24rpx;
            color: #999;
            text-decoration: line-through;
            margin-left: 10rpx;
          }
        }

        .cart-btn {
          width: 40rpx;
          height: 40rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #fef0f0;
          border-radius: 50%;

          &:active {
            opacity: 0.7;
          }
        }
      }

      .sold-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12rpx;

        .sold-count {
          font-size: 28rpx;
          color: #999;
        }
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.seckill-goods {
  margin: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10rpx;
    margin-bottom: 20rpx;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .more {
      font-size: 24rpx;
      color: #999;
    }
  }

  .seckill-items {
    .seckill-item {
      display: flex;
      padding: 20rpx 10rpx;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .goods-image {
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        flex-shrink: 0; // 防止图片被压缩
      }

      .goods-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 20rpx;
        min-width: 0; // 防止文字溢出

        .goods-name {
          font-size: 28rpx;
          color: #333;
          font-weight: bold;
          line-height: 1.4;
          margin-bottom: 10rpx;
          @include text-ellipsis;
        }

        .goods-desc {
          font-size: 24rpx;
          color: #666;
          line-height: 1.4;
          margin-bottom: 10rpx;
          @include text-ellipsis;
        }

        .remain-info {
          margin-bottom: 10rpx;

          .remain-text {
            font-size: 24rpx;
            color: #ff4444;
          }
        }

        .price-action {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price-info {
            .current-price {
              font-size: 32rpx;
              color: #ff4444;
              font-weight: bold;
            }

            .original-price {
              font-size: 24rpx;
              color: #999;
              text-decoration: line-through;
              margin-left: 10rpx;
            }
          }

          .buy-btn {
            margin: 0;
            padding: 0 20rpx;
            height: 56rpx;
            line-height: 56rpx;
            font-size: 24rpx;
            color: #fff;
            background-color: #ff4444;
            border-radius: 28rpx;

            &:active {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
}

.search-container {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  :deep(.uni-searchbar) {
    padding: 0;

    .uni-searchbar__box {
      height: 70rpx;
      padding: 0 20rpx;
      background-color: #f5f5f5;
      border-radius: 35rpx;
    }

    .uni-searchbar__text-input {
      font-size: 28rpx;
      color: #333;
    }

    .uni-searchbar__text {
      font-size: 28rpx;
      color: #999;
    }
  }
}
</style>
